/**
 * Configuration Management
 * 
 * Loads and validates configuration from environment variables
 */

import type { Config, ClaudeModel } from '@/types';

/**
 * Load configuration from environment variables
 */
export function loadConfig(): Config {
  const env = process.env;

  // Validate required environment variables
  const anthropicApiKey = env.ANTHROPIC_API_KEY;
  if (!anthropicApiKey) {
    throw new Error('ANTHROPIC_API_KEY environment variable is required');
  }

  return {
    // API Configuration
    anthropicApiKey,

    // Server Configuration
    port: parseInt(env.PORT || '3000', 10),
    host: env.HOST || '127.0.0.1',

    // Agent Configuration
    defaultModel: (env.DEFAULT_MODEL || 'claude-sonnet-4') as ClaudeModel,
    maxTurns: parseInt(env.MAX_TURNS || '10', 10),
    maxTokens: parseInt(env.MAX_TOKENS || '4096', 10),

    // MCP Configuration
    mcpServersDir: env.MCP_SERVERS_DIR || './mcp-servers',

    // Security
    enableCors: env.ENABLE_CORS === 'true',
    allowedOrigins: env.ALLOWED_ORIGINS?.split(',') || ['http://localhost:1420', 'tauri://localhost'],

    // Performance
    enableCache: env.ENABLE_CACHE === 'true',
    cacheTtl: parseInt(env.CACHE_TTL || '3600', 10),

    // Logging
    logLevel: (env.LOG_LEVEL || 'info') as 'debug' | 'info' | 'warn' | 'error',
  };
}

/**
 * Global configuration instance
 */
export const config = loadConfig();

/**
 * Get configuration value
 */
export function getConfig<K extends keyof Config>(key: K): Config[K] {
  return config[key];
}

/**
 * Validate configuration
 */
export function validateConfig(cfg: Config): void {
  // Validate API key (skip in test environment or when SKIP_API_KEY_CHECK is set)
  const isTest = process.env.NODE_ENV === 'test' || process.env.BUN_ENV === 'test';
  const skipApiKeyCheck = process.env.SKIP_API_KEY_CHECK === 'true';
  if (!isTest && !skipApiKeyCheck && (!cfg.anthropicApiKey || cfg.anthropicApiKey === 'your_api_key_here')) {
    console.warn('⚠️  Warning: ANTHROPIC_API_KEY not configured. Agent query features will not work.');
    console.warn('   Set SKIP_API_KEY_CHECK=true in .env to suppress this warning.');
  }

  // Validate port
  if (cfg.port < 1 || cfg.port > 65535) {
    throw new Error(`Invalid PORT: ${cfg.port}. Must be between 1 and 65535`);
  }

  // Validate model
  const validModels: ClaudeModel[] = ['claude-opus-4', 'claude-sonnet-4', 'claude-sonnet-4.5', 'claude-haiku-4'];
  if (!validModels.includes(cfg.defaultModel)) {
    throw new Error(`Invalid DEFAULT_MODEL: ${cfg.defaultModel}. Must be one of: ${validModels.join(', ')}`);
  }

  // Validate max turns
  if (cfg.maxTurns < 1) {
    throw new Error(`Invalid MAX_TURNS: ${cfg.maxTurns}. Must be at least 1`);
  }

  // Validate max tokens
  if (cfg.maxTokens < 1) {
    throw new Error(`Invalid MAX_TOKENS: ${cfg.maxTokens}. Must be at least 1`);
  }
}

// Validate configuration on load
validateConfig(config);

